package com.tj.jinzao.wxapi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.SubscribeMessage;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessView;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessWebview;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tj.jinzao.App;
import com.tj.jinzao.R;
import com.tj.jinzao.activity.AccountManagerActivity;
import com.tj.jinzao.activity.CompleteInfoActivity;
import com.tj.jinzao.activity.LoginActivity;
import com.tj.jinzao.activity.MainActivity;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.manager.ExitBind;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.utils.NetworkUtil;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Util;
import com.tj.jinzao.widgets.CustomWaitDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

	private static String TAG = "MicroMsg.WXEntryActivity";

	private IWXAPI api;
	private MyHandler handler;
	protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

	private CompositeSubscription mCompositeSubscription;
	public void detachView() {
		onUnsubscribe();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		detachView();
	}
	public void addSubscription(Observable observable, Subscriber subscriber) {
		if (mCompositeSubscription == null) {
			mCompositeSubscription = new CompositeSubscription();
		}
		mCompositeSubscription.add(observable
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(subscriber));
	}

	//RXjava取消注册，以避免内存泄露
	public void onUnsubscribe() {
		if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
			mCompositeSubscription.unsubscribe();
		}
	}

	private class MyHandler extends Handler {
		private final WeakReference<WXEntryActivity> wxEntryActivityWeakReference;

		public MyHandler(WXEntryActivity wxEntryActivity){
			wxEntryActivityWeakReference = new WeakReference<WXEntryActivity>(wxEntryActivity);
		}

		@Override
		public void handleMessage(Message msg) {
			int tag = msg.what;
			switch (tag) {
				case NetworkUtil.GET_TOKEN: {
					Bundle data = msg.getData();
					JSONObject json = null;
					try {
						json = new JSONObject(data.getString("result"));
						String openId, accessToken, refreshToken, scope,unionid;
						openId = json.getString("openid");
						unionid = json.getString("unionid");
						accessToken = json.getString("access_token");
						refreshToken = json.getString("refresh_token");
						scope = json.getString("scope");
						App.open_id=openId;
						if(!App.isShare){
							if(App.type_bind==1){
								getBind(unionid);
							}else {
								wxLogin(unionid);
							}

						}else {
							//初始化一个WXWebpageObject，填写url
							WXWebpageObject webpage = new WXWebpageObject();
							webpage.webpageUrl ="https://nian.im/early/share.html";


//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
							WXMediaMessage msgs = new WXMediaMessage(webpage);
							msgs.title ="尽早 ";
							msgs.description ="尽早app下载";
							Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
							msgs.thumbData = Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
							SendMessageToWX.Req req = new SendMessageToWX.Req();
							req.transaction = buildTransaction("webpage");
							req.message =msgs;
							req.scene =App.type;
							req.userOpenId = App.open_id;
//调用api接口，发送数据到微信
							api.sendReq(req);

						}
						Log.w("微信登录==",""+openId+"=="+unionid);
//						Intent intent = new Intent(wxEntryActivityWeakReference.get(), SendToWXActivity.class);
//						intent.putExtra("openId", openId);
//						intent.putExtra("accessToken", accessToken);
//						intent.putExtra("refreshToken", refreshToken);
//						intent.putExtra("scope", scope);
//						wxEntryActivityWeakReference.get().startActivity(intent);
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage());
					}
				}
			}
		}
	}
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	public CustomWaitDialog progressDialog = null;

	public void startProgressDialog(Context context) {
		if (progressDialog == null) {
			progressDialog = new CustomWaitDialog(context);
		}
		progressDialog.show();
	}

	public void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
	private void getBind(String wxId){
		startProgressDialog(this);
		HashMap<String,Object> map=new HashMap<>();
		map.put("uid",UserManager.getInstance().getUser().getId());
		map.put("openid",wxId);
		map.put("type","weixin");
		Log.w("数据额搬到",""+map.toString());
		addSubscription(mApiService.getBindWX(map), new SubscriberCallBack<ExitBind>(WXEntryActivity.this) {
			@Override
			protected void onSuccess(ExitBind exitBind) {
				stopProgressDialog();
				User user=UserManager.getInstance().getUser();
				user.setOpenid(wxId);
				UserManager.saveUserData(user);
				finish();
				Log.w("数据额搬到","666");
			}

			@Override
			protected void onFailure(ResultResponse response) {
				stopProgressDialog();
				User user=UserManager.getInstance().getUser();
				user.setOpenid("");
				UserManager.saveUserData(user);
				finish();
				Log.w("数据额搬到","888");
			}
			@Override
			protected void onStringNull(ResultResponse response) {

			}
		});

	}

	private void wxLogin(String openId){
		startProgressDialog(WXEntryActivity.this);
		HashMap<String,Object> hashMap=new HashMap<>();
		hashMap.put("openid",openId);
		hashMap.put("source","2");
		addSubscription(mApiService.getWXLogin(hashMap), new SubscriberCallBack<User>(this) {
			@Override
			protected void onSuccess(User user) {
				loginChat(user);
			}

			@Override
			protected void onFailure(ResultResponse response) {
			    stopProgressDialog();
                finish();

			}

			@Override
			protected boolean isShowProgress() {
				return false;
			}

			@Override
			protected void onPageSuccess(int currentPage, int allPage, int allSize) {
			}
		});

	}
	public void loginChat(final User user) {
		NimUIKit.login(new LoginInfo(String.valueOf(user.getYunxinAccount()), "123456"), new RequestCallback<LoginInfo>() {
			@Override
			public void onSuccess(LoginInfo param) {
				stopProgressDialog();
                finish();
				LogUtil.i("wjy", "login success");
				// 初始化消息提醒配置
				NIMClient.toggleNotification(true);
				UserManager.saveUserData(user);
				// 进入主界面
				if (TextUtils.isEmpty(user.getMobile())) {
					Intent to=new Intent();
					to.putExtra("typeLogin",1);
					to.setClass(WXEntryActivity.this,LoginActivity.class);
					startActivity(to);
				} else {
					if (UserManager.getInstance().getUser().getGender() == 3) {
						Intent to=new Intent();
						to.putExtra("typeLogin",2);
						to.setClass(WXEntryActivity.this,LoginActivity.class);
						startActivity(to);
					}else {
						startActivity(new Intent(WXEntryActivity.this, MainActivity.class));
					}

				}

			}

			@Override
			public void onFailed(int code) {
                stopProgressDialog();
                finish();
					if (code == 302 || code == 404) {
						ToastUtils.showToast(WXEntryActivity.this, "帐号或密码错误");
					} else {
						ToastUtils.showToast(WXEntryActivity.this, "登录失败: " + code);
					}
			}

			@Override
			public void onException(Throwable exception) {
					ToastUtils.showToast(WXEntryActivity.this, "login_exception");
			}
		});
		updateUserInfo(user);
	}
	public void updateUserInfo(final User user){
		Map<UserInfoFieldEnum, Object> fields = new HashMap<>();
		fields.put(UserInfoFieldEnum.Name,user.getNickname());
		fields.put(UserInfoFieldEnum.AVATAR, Constant.IMAGE_PREFIX+user.getImgurl());
		NIMClient.getService(UserService.class).updateUserInfo(fields)
				.setCallback(new RequestCallbackWrapper<Void>() {
					@Override
					public void onResult(int i, Void aVoid, Throwable throwable) {
					}
				});

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		api = WXAPIFactory.createWXAPI(this, Constant.WX_APPID, false);
		handler = new MyHandler(this);

		try {
			Intent intent = getIntent();
			api.handleIntent(intent, this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);
	}

	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
			case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
				goToGetMsg();
				break;
			case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
				goToShowMsg((ShowMessageFromWX.Req) req);
				break;
			default:
				break;
		}
		if(App.isShare==true){
			finish();
		}

//		finish();
	}

	@Override
	public void onResp(BaseResp resp) {
		String result = "";

		switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK:
				result = "发送成功";
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL:
				result = "发送返回";
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				result = "发送拒绝";
				break;
			case BaseResp.ErrCode.ERR_UNSUPPORT:
				result = "不支持错误";
				break;
			default:
				result = "qq";
				break;
		}
//		Log.w("微信登录","999");
//		Toast.makeText(this, result + ", type=" + resp.openId, Toast.LENGTH_SHORT).show();


		if (resp.getType() == ConstantsAPI.COMMAND_SUBSCRIBE_MESSAGE) {
			SubscribeMessage.Resp subscribeMsgResp = (SubscribeMessage.Resp) resp;
			String text = String.format("openid=%s\ntemplate_id=%s\nscene=%d\naction=%s\nreserved=%s",
					subscribeMsgResp.openId, subscribeMsgResp.templateID, subscribeMsgResp.scene, subscribeMsgResp.action, subscribeMsgResp.reserved);

			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
			WXLaunchMiniProgram.Resp launchMiniProgramResp = (WXLaunchMiniProgram.Resp) resp;
			String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s",
					launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr);

			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_VIEW) {
			WXOpenBusinessView.Resp launchMiniProgramResp = (WXOpenBusinessView.Resp) resp;
			String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s\nbusinessType=%s",
					launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr,launchMiniProgramResp.businessType);

			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_WEBVIEW) {
			WXOpenBusinessWebview.Resp response = (WXOpenBusinessWebview.Resp) resp;
			String text = String.format("businessType=%d\nresultInfo=%s\nret=%d",response.businessType,response.resultInfo,response.errCode);

			Toast.makeText(this, text, Toast.LENGTH_LONG).show();
		}

		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			SendAuth.Resp authResp = (SendAuth.Resp)resp;
			final String code = authResp.code;
			NetworkUtil.sendWxAPI(handler, String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
							"appid=%s&secret=%s&code=%s&grant_type=authorization_code", "wxd16250ccb9487cf9",
					"d79010c15ca0574750d40faff71add69", code), NetworkUtil.GET_TOKEN);
		}
		if(App.isShare==true){
			finish();
		}
	}

	private void goToGetMsg() {
//		Intent intent = new Intent(this, InviteFriendActivity.class);
//		intent.putExtras(getIntent());
//		startActivity(intent);
//		finish();
	}

	private void goToShowMsg(ShowMessageFromWX.Req showReq) {
		WXMediaMessage wxMsg = showReq.message;
		WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

		StringBuffer msg = new StringBuffer();
		msg.append("description: ");
		msg.append(wxMsg.description);
		msg.append("\n");
		msg.append("extInfo: ");
		msg.append(obj.extInfo);
		msg.append("\n");
		msg.append("filePath: ");
		msg.append(obj.filePath);

//		Intent intent = new Intent(this, ShowFromWXActivity.class);
//		intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
//		intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
//		intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
//		startActivity(intent);
//		finish();
	}


}